/**
 * Created by Administrator on 2015/11/24.
 */
var Message = require('../domain/domain').Message
var Comment = require('../domain/domain').Comment
var User = require('../domain/domain').User
var utils = require('utility')
var helper = require('./helper')


module.exports = function (app) {

    app.get("/recipe/details/:id", function *() {
        var $self = this
        var id = +$self.params.id
        if (!id) {
            $self.status = 404
            return
        }
        var sqls = [
            "SELECT R.id, R.title, R.finishedProductImage, R.backgroundStory, R.ingredient, R.seasoning, R.step, R.knack, R.keyword, R.upvote, R.isRaw, R.createOn, R.comment, R.collect",
            ", U.id AS 'user.id', U.nick AS 'user.nick', U.portrait AS 'user.portrait', U.menuCount AS 'user.count.menu', U.recipeCount AS 'user.count.recipe' ",
            ", U.focusCount AS 'user.count.focus', U.fansCount AS 'user.count.fans', Ctg.id AS 'category.id', Ctg.name AS 'category.name', CL.id AS 'level.id', CL.name AS 'level.name' ",
            ", CL.level AS 'level.level', CD.id AS 'diff.id', CD.name AS 'diff.name', CD.level AS 'diff.level', CS.id AS 'spend.id', CS.name AS 'spend.name', CS.spend AS 'spend.spend' ",
            ", CW.id AS 'craftwork.id', CW.name AS 'craftwork.name', F.id AS 'flavour.id', F.name AS 'flavour.name' ",
            "FROM Recipe R, User U, RecipeCtg Ctg, CookieDiff CD, CookieLevel CL, CookieSpend CS, Craftwork CW, Flavour F",
            "WHERE R.id=? AND R.owner_id=U.id AND R.category_id=Ctg.id AND R.cookie_level_id=CL.id AND R.cookie_diff_id=CD.id AND R.cookie_spend_id=CS.id",
            "AND R.craftwork_id=CW.id AND R.flavour_id=F.id"
        ]
        var recipe = yield $self.db(sqls.join(' '), id).unique()
        recipe = helper.params2obj(recipe)
        var user = new User($self.session.user)
        var collected = yield user.has$collect$recipe($self, id)
        var upvoted = yield user.has$upvote$recipe($self, id)
        if(recipe.ingredient)
            recipe.ingredient = JSON.parse(recipe.ingredient)
        if(recipe.step)
            recipe.step = JSON.parse(recipe.step)
        yield $self._render('recipe/details', {
            title: recipe.title,
            recipe: recipe,
            collected: collected,
            upvoted: upvoted,
            dateformat: utils.YYYYMMDD
        })
    })

    /**
     * =========菜谱列表=========
     */
    app.get('/recipe/categories', function *() {
        var $self = this
        var ctgs = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id IS NULL').list()
        yield (function *(collects) {
            var callee = arguments.callee
            for(var i=0; i<collects.length; i++){
                var array = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id=?', collects[i].id).list()
                if(array.length > 0){
                    yield callee(array)
                    collects[i].children = array
                }
            }
        })(ctgs)
        $self.body = {
            categories: ctgs
        }
    })

    /**
     *   =========删除==========
     */
    app.get("/recipe/delete/:id", function *() {
        var $self = this
        var id = $self.params.id

        console.log('id =====' + id)
        if (!id) {
            $self.status = 404;
            return
        }
        yield $self.db('DELETE FROM Recipe WHERE id = ?', id).execute();
    })


    /**
     *   =========更新==========
     */
    //app.get("/recipe/update/")

    /**
     *  =========用户对菜谱点赞===========
     */
    app.post('/user/private/recipe/:rid/upvote', function *() {
        var $self = this
        var upvote = {
            uid: $self.session.user.id,
            rid: $self.params.rid,
            createOn: new Date()
        }
        try{
            yield $self.db('INSERT INTO RecipeUpvote SET ?', upvote).execute()
        }catch(err){
            console.error(err.stack)
            this.body = {
                code: 403,
                message: '你已经点赞过啦'
            }
            return
        }
        yield $self.db('UPDATE Recipe SET upvote = upvote +1 WHERE id=?', $self.params.rid).execute()
        var recipe = yield $self.db('SELECT owner_id FROM Recipe WHERE id=?', upvote.rid).unique()
        var message = new Message()
        message.user_id = upvote.uid
        message.another_id = recipe.owner_id
        message.obj_id = upvote.rid
        message.type = Message.TYPE_UPVOTE_RECIPE
        message.another_already_read = false
        delete message.id
        yield $self.db('INSERT INTO Message SET ?', message).execute()
        this.body = {
            code: 0,
            message: '已点赞!'
        }
    })

    /**
     * ============用户收藏菜谱============
     */
    app.post('/user/private/recipe/:rid/collect', function *() {
        var $self = this
        var collect = {
            uid: $self.session.user.id,
            rid: $self.params.rid,
            createOn: new Date()
        }
        try{
            yield $self.db('INSERT INTO RecipeCollect SET ?', collect).execute()
        }catch(err){
            console.log(err.track)
            this.body = {
                code: 403,
                message: '你已经收藏过啦！'
            }
            return
        }

        yield $self.db('UPDATE Recipe SET collect = collect + 1 WHERE id=?', $self.params.rid).execute()
        this.body = {
            code: 0,
            message: '已收藏'
        }
    })

    /**
     * ===========用户评论菜谱===========
     */
    app.post('/user/private/recipe/:rid/comment', function *() {
        var $self = this
        var body = $self.request.body
        var comment = new Comment(body)
        delete comment.id
        comment.user_id = $self.session.user.id
        comment.obj_id = $self.params.rid
        comment.type = Comment.TYPE_RECIPE
        yield $self.db('INSERT INTO Comment SET ?', comment).execute()
        var recipe = yield $self.db('SELECT id, owner_id WHERE id=?', $self.params.rid).unique()
        var message = new Message()
        message.user_id = $self.session.user.id
        message.another_id = recipe.owner_id
        message.obj_id = $self.params.rid
        message.type = Message.TYPE_COMMENT_RECIPE
        message.another_already_read = false
        delete message.id
        yield $self.db('INSERT INTO Message SET ?', message).execute()
        $self.response.redirect('/recipe/details/'+$self.params.rid+'#comment')
    })


}